package com.sp.fresh_produce.web;

import com.sp.fresh_produce.common.Constant;
import com.sp.fresh_produce.model.pojo.User;
import com.sp.fresh_produce.service.UserService;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * 用户过滤器
 */
public class UserFilter implements Filter {

    public static  User currentUser;

    @Autowired
    private UserService userService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        currentUser = (User) session.getAttribute(Constant.USER_SESSION_KEY);
        // 如果用户未登录，返回需要登录的错误
        if (currentUser == null) {
            PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse) servletResponse).getWriter();
            out.write("{\n" +
                    "  \"status\": 10007,\n" +
                    "  \"msg\": \"NEED_LOGIN\",\n" +
                    "  \"data\": null\n" +
                    "}");
            out.flush();
            out.close();
            // 阻止后续过滤器执行，避免重复处理
            return;
        }
        // 如果用户已登录，则继续执行后续过滤器
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
